<template>
  <div id="app">
    <div>
      <span>姓名:</span>
      <input type="text" v-model.trim="iptName"/>
    </div>
    <div>
      <span>年龄:</span>
      <input type="number" v-model="iptAge"/>
    </div>
    <div>
      <span>性别:</span>
      <select v-model="iptSex">
        <option value="男">男</option>
        <option value="女">女</option>
      </select>
    </div>
    <div>
      <button @click="updata">添加/修改</button>
    </div>
    <div>
      <table
        border="1"
        cellpadding="10"
        cellspacing="0"
      >
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
        <tr v-for="(item, index) in list" :key="index">
          <td>{{ index + 1 }}</td>
          <td>{{ item.name }}</td>
          <td>{{ item.age }}</td>
          <td>{{ item.sex }}</td>
          <td>
            <button @click="delFn(index)">删除</button>
            <button @click="revise(index)">编辑</button>
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>
<script>
// 目标：实现学生信息管理
export default {
  data() {
    return {
      list: [
        {
          name: '张三',
          age: 18,
          sex: '男'
        },
        {
          name: '李四',
          age: 18,
          sex: '男'
        }
      ],
      iptName: '',
      iptAge: '',
      iptSex: '',
      flag: -1  //添加 / 修改标记
    }
  },
  methods: {
    // 更新方法
    updata(){
      if(!this.iptName || !this.iptAge || !this.iptSex) return alert('输入信息不合理，请检查一下！！')
      
      if(this.flag >= 0){
        console.log(this.flag);
          this.list.splice(this.flag, 1, {
          name: this.iptName,
          age: this.iptAge,
          sex: this.iptSex,
        })
        this.flag = -1
      }else{
        this.list.push({
          name: this.iptName,
          age: this.iptAge,
          sex: this.iptSex
        })  
      }
      this.iptName = '',
      this.iptAge = '',
      this.iptSex = ''
      
    },
    // 编辑功能
    revise(index){
      this.iptName = this.list[index].name
      this.iptAge = this.list[index].age
      this.iptSex = this.list[index].sex
      this.flag = index

    },
    // 删除功能
    delFn(index){
      this.flag = -1  //防止点击编辑后直接点击添加影响原数据
      this.list.splice(index, 1)
    }
  },
}
</script>
